<template>
  <DraggableModal :visible="props.showModal" title="新增冻存盒" width="600px" @cancel="modalCancelFn">
    <Form ref="formRef" :model="state.data" :rules="rules" :label-col="{ span: 8 }">
      <a-form-item :label="$t('specimen.Box_type')" name="boxSerial">
        <Select v-model:value="state.data.boxSerial" style="width: 50%" :fieldNames="{ label: 'label', value: 'label' }" :options="boxTypeList" />
      </a-form-item>
      <a-form-item label="是否需要自定义编码" name="color">
        <Checkbox v-model:checked="state.btnChecked" />
      </a-form-item>
      <a-form-item v-if="state.btnChecked" label="自定义编码">
        <Tag v-for="(item, index) in state.data.epcs" :key="item.prefix" closable style="margin: 0 5px 5px 0" @close="deleteEpcsFn(index)">
          <span v-if="item.prefix && item.start && item.end">{{ `${item.prefix}-${item.start}~${item.prefix}-${item.end}` }} </span>
          <span v-if="item.prefix && item.start && !item.end">
            {{ `${item.prefix}-${item.start}` }}
          </span>
          <span v-if="item.prefix && !item.start">{{ item.prefix }}</span>
        </Tag>
        <Popconfirm @confirm="formOkFn" @cancel="formCancelFn">
          <template #icon></template>
          <Button type="dashed" style="height: 30px; line-height: 20px; margin-top: 5px"> <plus-outlined />添加实体 </Button>
          <template #title>
            <Space>
              <Input style="width: 100px" placeholder="序列号前缀" min="1" v-model:value="state.formData.prefix" />
              <Input style="width: 100px" placeholder="起始序列号" min="1" v-model:value="state.formData.start" />
              <Input style="width: 100px" placeholder="结束序列号" min="1" v-model:value="state.formData.end" />
            </Space>
          </template>
        </Popconfirm>
      </a-form-item>
      <a-form-item v-else label="打印数量" name="count">
        <InputNumber min="1" v-model:value="state.data.count" />
      </a-form-item>
    </Form>

    <template #footer>
      <Button @click="modalCancelFn">取消</Button>
      <Button type="primary" @click="modalOkFn">保存</Button>
    </template>
  </DraggableModal>
</template>

<script setup lang="ts">
import { DraggableModal } from '@/framework/components/core/draggable-modal';
import { reactive, ref } from 'vue';
import Button from '@/framework/components/basic/button/button.vue';
import { Form, Input, Checkbox, InputNumber, message, Select, Popconfirm, Space, Tag } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import _ from 'lodash-es';
import { postInstanceAddV2, boxPrint } from '@/api/base/box_data';
import { iceboxConfig } from '@/api/base/systemSetup_data';
import { boxTypeList } from '../columns';

type FormData = { prefix: string; start: string; end: string };
type State = {
  data: {
    boxSerial?: string;
    count: number;
    epcs: FormData[];
  };
  btnChecked: boolean;
  formData: FormData;
  isSupportIntelligentIcebox: boolean;
};
const props = withDefaults(
  defineProps<{
    showModal: boolean;
  }>(),
  {
    showModal: false,
  },
);
const emits = defineEmits<{
  (e: 'update:showModal', state: boolean): void;
  (e: 'addBoxModalOk'): void;
}>();
const formRef = ref<FormInstance>();

/**
 * data
 */
const state: State = reactive({
  data: {
    count: 1,
    epcs: [],
  },
  btnChecked: true,
  formData: {
    prefix: '',
    start: '',
    end: '',
  },
  isSupportIntelligentIcebox: false,
}) as State;
const rules = {
  boxSerial: [{ required: true, message: '数据必填', trigger: 'change' }],
  count: [{ required: true, message: '数据必填', trigger: 'change', type: 'integer' }],
};
/**
 * add/edit modal
 */
const modalOkFn = async () => {
  try {
    await formRef.value?.validateFields();
  } catch {
    return message.warn('数据有误，请检查后重试！');
  }
  if (!state.data.epcs.length && state.btnChecked) {
    return message.warn('请添加编码！');
  }
  if (state.btnChecked) {
    await postInstanceAddV2(state.data);
  } else {
    await boxPrint(state.data);
  }
  message.success('保存成功！');
  modalCancelFn();
  emits('addBoxModalOk');
};
const modalCancelFn = () => {
  emits('update:showModal', false);
  formRef.value?.resetFields();
  state.data.epcs = [];
};

/**
 * form
 */
const formOkFn = () => {
  if (!state.formData.prefix.trim().length) {
    return message.warn('序列号前缀不能为空！');
  }
  const params = _.cloneDeep(state.formData);
  state.data.epcs.push(params);
  formCancelFn();
};
const formCancelFn = () => {
  state.formData = {
    prefix: '',
    start: '',
    end: '',
  };
};
const deleteEpcsFn = (index: number) => {
  state.data.epcs.splice(index, 1);
};

/**
 * fn
 */
// 获取是否智能冰箱
const getSupportIntelligentIcebox = async () => {
  let params = {
    orderBy: [
      {
        field: 'createTime',
        order: 'asc',
      },
    ],
    groupId: 'support_icebox_config',
  };
  try {
    const res = await iceboxConfig(params);
    state.isSupportIntelligentIcebox = !!res.result.find((item) => item.key == 'intelligent_icebox' && item.value === '1');
  } catch (err) {
    console.log('获取出入库方式配置-出错', err);
  }
};
getSupportIntelligentIcebox();
</script>

<style scoped lang="less"></style>
